package com.gitee.hermer.boot.jee.api.auto.configuration;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "com.boot.jee.api.swagger", value = "enable",havingValue="true",matchIfMissing = false)  
public class SwaggerConfiguration extends UtilsContext{



	@Bean
	public Docket getSwaggerSpringMvcPlugin(ApplicationContext context){
		String apiSuffix = getDictValue("com.boot.jee.upms.mapping.api.suffix", "/apirestful");


		String pathMapping = null;
		Map<String, HandlerMapping>  mapping = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false); 

		Map<RequestMappingInfo, HandlerMethod> mappings = ((RequestMappingHandlerMapping)mapping.get("requestMappingHandlerMapping")).getHandlerMethods();
		i:for (RequestMappingInfo info : mappings.keySet()) {
			String[] array = info.getPatternsCondition().getPatterns().toArray(new String[]{});
			for (int i = 0; i < array.length; i++) {
				if(StringUtils.isNotEmpty(array[i]) && array[i].indexOf(apiSuffix) != -1){
					pathMapping = apiSuffix+"/**";
					break i;
				}
			}
		}

		return new Docket(DocumentationType.SWAGGER_2)
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(pathMapping == null?PathSelectors.any():PathSelectors.ant(pathMapping))
				.build()
				.pathMapping("/")
				.directModelSubstitute(Date.class,
						String.class)
				.genericModelSubstitutes(ResponseEntity.class);

	}

}
